package cn.lingyangwl.agile.common.security.filter;

import cn.lingyangwl.agile.model.constants.RequestCons;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * websocket 前端将token放到子协议里传入 与后端建立连接时需要用到http协议，此处用于校验token的有效性
 * @author shenguangyang
 */
@Slf4j
@Component
public class WebSocketFilter implements Filter {

    /**
     * 注意, 这里必须设置响应头为 {@link RequestCons.Headers#WEB_SOCKET_TOKEN}, 否则网关会报错
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String token = request.getHeader(RequestCons.Headers.WEB_SOCKET_TOKEN);
        if (StringUtils.isEmpty(token)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        response.setHeader(RequestCons.Headers.WEB_SOCKET_TOKEN, token);
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
